package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.aspect
 */
//@Aspect
@Slf4j
//@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    // 参数二的作用：代表切入点表达式，注解
    public Object around(ProceedingJoinPoint pjp, LogOperation log) throws Throwable {
        OperateLog operationLog = new OperateLog();
        // 操作的时间
        operationLog.setOperateTime(LocalDateTime.now());
        long begin = System.currentTimeMillis();
        // 设置属性值
        // 获取它的类型
        String clsName = pjp.getTarget().getClass().getName();
        operationLog.setClassName(clsName);
        // 获取方法名称
        String methodName = pjp.getSignature().getName();
        operationLog.setMethodName(methodName);
        // 获取方法参数
        Object[] args = pjp.getArgs();
        operationLog.setMethodParams(Arrays.toString(args));
        //调用原始方法
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        // 接口耗时
        operationLog.setCostTime(end-begin);
        // 登录用户的id
        operationLog.setOperateEmpId(CurrentHolder.getCurrentId());
        //方法的返回值
        operationLog.setReturnValue(result.toString());
        operateLogMapper.insert(operationLog);
        // 异步保存日志，不好，优化，使用线程池???
        new Thread(()->operateLogMapper.insert(operationLog)).start();
        return result;
    }
}
